// src/services/comments.js - 评论系统服务

import { get, post } from './api';

// 本地存储key
const COMMENTS_STORAGE_KEY = 'starrypt_comments';

// 初始化本地存储数据
export const initCommentsData = () => {
  if (!localStorage.getItem(COMMENTS_STORAGE_KEY)) {
    localStorage.setItem(COMMENTS_STORAGE_KEY, JSON.stringify([]));
  }
};

// 本地存储操作
const localGetComments = (postId = null) => {
  const comments = JSON.parse(localStorage.getItem(COMMENTS_STORAGE_KEY) || '[]');
  return postId ? comments.filter(comment => comment.topicId === postId) : comments;
};

const localCreateComment = (commentData) => {
  const comments = localGetComments();
  const newComment = {
    id: Date.now(),
    commentId: Date.now(),
    ...commentData,
    createTime: new Date().toISOString(),
    likes: 0,
    author: JSON.parse(localStorage.getItem('starrypt_user') || 'null')?.username || 'Anonymous'
  };
  comments.push(newComment);
  localStorage.setItem(COMMENTS_STORAGE_KEY, JSON.stringify(comments));
  return { success: true, reply: newComment };
};

/**
 * 获取帖子评论
 * @param {number} postId - 帖子ID
 * @param {Object} params - 查询参数 {page, limit}
 * @returns {Promise} - 评论列表
 */
export const getPostComments = async (postId, params = {}) => {
  try {
    const query = new URLSearchParams();
    query.append('postId', postId);
    if (params.page) query.append('page', params.page);
    if (params.limit) query.append('limit', params.limit);

    const response = await get(`/comments/post?${query.toString()}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data
      };
    } else {
      return {
        success: false,
        message: response.message || '获取评论失败'
      };
    }
  } catch (error) {
    console.warn('获取评论API连接失败，使用本地存储:', error);

    const comments = localGetComments(postId);
    const page = params.page || 1;
    const limit = params.limit || 20;
    const total = comments.length;
    const totalPages = Math.ceil(total / limit);
    const start = (page - 1) * limit;
    const paginatedComments = comments.slice(start, start + limit);

    return {
      success: true,
      data: {
        replies: paginatedComments,
        pagination: {
          page: page,
          limit: limit,
          total: total,
          totalPages: totalPages
        }
      }
    };
  }
};

/**
 * 添加评论
 * @param {Object} commentData - 评论数据 {postId, content}
 * @returns {Promise} - 添加结果
 */
export const addComment = async (commentData) => {
  try {
    const response = await post('/comments/add', commentData);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data,
        message: response.message || '评论发布成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '评论发布失败'
      };
    }
  } catch (error) {
    console.warn('添加评论API连接失败，使用本地存储:', error);

    const result = localCreateComment(commentData);
    if (result.success) {
      return {
        success: true,
        message: '评论发布成功',
        data: { reply: result.reply }
      };
    } else {
      throw new Error('评论发布失败');
    }
  }
};

/**
 * 删除评论
 * @param {number} commentId - 评论ID
 * @returns {Promise} - 删除结果
 */
export const deleteComment = async (commentId) => {
  try {
    const query = new URLSearchParams();
    query.append('commentId', commentId);

    const response = await post(`/comments/delete?${query.toString()}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        message: response.message || '评论删除成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '评论删除失败'
      };
    }
  } catch (error) {
    console.warn('删除评论API连接失败:', error);
    throw new Error('删除评论失败: ' + error.message);
  }
};

/**
 * 点赞评论
 * @param {number} commentId - 评论ID
 * @returns {Promise} - 点赞结果
 */
export const likeComment = async (commentId) => {
  try {
    const query = new URLSearchParams();
    query.append('commentId', commentId);

    const response = await post(`/comments/like?${query.toString()}`);

    // 适配后端响应格式 {code: 200, message: "操作成功", data: {...}}
    if (response.code === 200) {
      return {
        success: true,
        data: response.data,
        message: response.message || '操作成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '点赞失败'
      };
    }
  } catch (error) {
    console.warn('点赞评论API连接失败:', error);
    throw new Error('点赞评论失败: ' + error.message);
  }
};

const commentsService = {
  initCommentsData,
  getPostComments,
  addComment,
  deleteComment,
  likeComment
};

export default commentsService; 